package OnlineExam.uploadquestions;

import java.sql.*;
import java.io.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;


/**
 *  Used to upload a question paper in an XML Formatt.
 */

public class QuestionsUploader 
{
    
    public static final String driver = "com.mysql.jdbc.Driver";
	public static final String url = "jdbc:mysql://localhost:3306/OnlineExam";
   	public static final String username ="root";
	public static final String password = "root";
	public static final String alphabets[] = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };

	static 
	{	
		try
		{
			Class.forName (driver);
		}
		catch (ClassNotFoundException cnfe)
    		{
    			System.err.println ("Error in loading the driver : " + cnfe);
    		}
	}
	
	private final static String xmlFileName = "QuestionPaper.xml";
    //private final static String targetFileName = "example2.xml";
    
	String question = new String();
	String options = new String();
	String[] opt = new String[10];
	String correctAnswer = new String();
	String explanation = new String();
	String categoryId = new String();
	int correctMarks = 0;
	int wrongMarks = 0;
	int optionLength = 0, count = 0;
		
    /** Creates a new instance of ParseXMLFile */
    public QuestionsUploader() 
	{
			
        // parse XML file -> XML document will be build
        Document doc = parseFile(xmlFileName);
        // get root node of xml tree structure
        Node root = doc.getDocumentElement();
        // write node and its child nodes into System.out
        System.out.println("Statemend of XML document...");
        writeDocumentToOutput(root);
        System.out.println("... end of statement");
        // write Document into XML file
        //saveXMLDocument(targetFileName, doc);
    }
    
    /* Returns element value */
	
    public final static String getElementValue( Node elem ) 
	{
        Node kid;
        if( elem != null)
		{
            if (elem.hasChildNodes())
			{
                for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() )
				{
                    if( kid.getNodeType() == Node.TEXT_NODE  )
					{
                        return kid.getNodeValue();
                    }
                }
            }
        }
        return "";
    }
    
    
    public void writeDocumentToOutput(Node node) 
	{
        // get element name
        String nodeName = node.getNodeName();
        // get element value
        String nodeValue = getElementValue(node);
		
		if (nodeName.equals ("Question"))
		{
			question = nodeValue;
		}
		else if (nodeName.equals ("CorrectAnswer"))
		{
			
			correctAnswer = mapOptionsToNumbers(nodeValue);
		}
		else if (nodeName.equals ("Explanation"))
		{
			explanation = nodeValue;
		}
		else if (nodeName.equals ("Options"))
		{
			options = new String();
			NodeList children = node.getChildNodes ();
			optionLength = children.getLength();
			for (int i = 0 , j = 0; i < children.getLength(); i++)
			{
				Node child = children.item(i);
				nodeValue = getElementValue(child);
				if (nodeValue != null && nodeValue != "" && nodeValue != "\n")
				{
					options = options.concat (nodeValue);
					options = options.concat(";;");
				}
			}
		}
		else if (nodeName.equals ("CorrectMarks"))
		{
			correctMarks = Integer.parseInt(nodeValue);
		}
		else if (nodeName.equals ("WrongMarks"))
		{
			wrongMarks = Integer.parseInt (nodeValue);
			System.out.println ("Question is.. " + question);
			System.out.println ("Chaitanya The Options are..." + options);
			System.out.println ("the correct answer.." + correctAnswer);
			System.out.println ("Explanation...... " + explanation);
			System.out.println ("the correct marks.." + correctMarks);
			System.out.println ("the wrong marks.." + wrongMarks);
			
			if (insertIntoDatabase (question, options, correctAnswer, explanation, correctMarks, wrongMarks))
			{
				System.out.println ("Done inserting " + (count++) + "th question" );
			}

		}
	
		// 
        // get attributes of element
        NamedNodeMap attributes = node.getAttributes();
        //System.out.println("NodeName: " + nodeName + ", NodeValue: " + nodeValue);
        
		for (int i = 0; i < attributes.getLength(); i++) 
		{
            Node attribute = attributes.item(i);
            System.out.println("AttributeName: " + attribute.getNodeName() +", attributeValue: " + attribute.getNodeValue());
        }
		
		/*if ((attribute.getNodeName()).equals("categoryId"))
		{
			categoryId = attribute.getNodeValue();
		}*/
		
        // write all child nodes recursively
        NodeList children = node.getChildNodes();
        
		for (int i = 0; i < children.getLength(); i++) 
		{
            Node child = children.item(i);
            if (child.getNodeType() == Node.ELEMENT_NODE) 
			{
                writeDocumentToOutput(child);
            }
        }
    }
    
    public Document parseFile(String fileName) 
	{
        System.out.println("Parsing XML file... " + fileName);
        DocumentBuilder docBuilder;
        Document doc = null;
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        docBuilderFactory.setIgnoringElementContentWhitespace(true);
        
		try 
		{
            docBuilder = docBuilderFactory.newDocumentBuilder();
        }
        catch (ParserConfigurationException e) 
		{
            System.out.println("Wrong parser configuration: " + e.getMessage());
            return null;
        }
        
		File sourceFile = new File(fileName);
        
		try 
		{
            doc = docBuilder.parse(sourceFile);
        }
        catch (SAXException e) 
		{
            System.out.println("Wrong XML file structure: " + e.getMessage());
            return null;
        }
        catch (IOException e) 
		{
            System.out.println("Could not read source file: " + e.getMessage());
        }
        System.out.println("XML file parsed");
        return doc;
    }

	
	private boolean insertIntoDatabase (String question, String options, String correctAnswer, 
					String explanation, int correctMarks, int wrongMarks)
	{
		//Session session = null;
		try
		{
			Connection connection = DriverManager.getConnection (url, username, password);
			Statement statement = connection.createStatement ();
			
			String queryToInsert = "insert into QuestionBank (CategoryId, Question, Options, " +
					"CorrectAnswer, Explanation, CorrectMarks, WrongMarks) values ('CS', '" + question + "','" 
					+ options + "','" + correctAnswer + "','" + explanation + "','" + correctMarks + "','" 
					 + wrongMarks + "')";
			
			statement.execute (queryToInsert);
			
			/*Questions q = new Questions();
			SessionFactory sessionFactory = new Configuration().buildSessionFactory();
			Session session = sessionFactory.openSession();
			Transaction tx = session.beginTransaction();
			q.setCategoryId ("CS");
			q.setQuestion (question);
			q.setOptions (options);
			q.setCorrectAnswer (correctAnswer);
			q.setExplanation (explanation);
			q.setCorrectMarks (correctMarks);
			q.setWrongMarks (wrongMarks);
			session.save(q);
			tx.commit();*/
			
			connection.close();
			return true;
		}
		catch (Exception e)
		{
			System.out.println ("Exception .." + e);
			return false;
		}
		/*finally 
		{
			session.flush();
			session.close();
		}*/

	}
			
   private String mapOptionsToNumbers (String nodeValue)
   {
		for (int i = 0; i < alphabets.length; i++)
		{
			if (alphabets[i].equals(nodeValue))
				return Integer.toString(i+1);
		}
		return null;
   } 
   	
    /* Starts XML parsing  */

    public static void main(String[] args) {
        new QuestionsUploader();
    }
    
}
